package utils

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"github.com/cihub/seelog"
	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
	"io/ioutil"
	"net/url"
	"wangchunguang_blog/system"
)

func Backup() (err error) {
	var (
		url         *url.URL // ur地址
		exist       bool     //是否存在
		ret         PutRet   // json返回值值字段构造
		bodyBytes   []byte   // 存放的字节
		encryptData []byte   // 加密后的数据
	)
	// 解析数据库地址
	url, err = url.Parse(system.GetConfiguration().DSN)
	if err != nil {
		seelog.Debug("parse dsn error:%v", err)
		return
	}
	exist, _ = PathExists(url.Path)
	if !exist {
		err = errors.New("database file doesn't exists.")
		seelog.Debug("database file doesn't exists.")
		return
	}
	seelog.Debug("start backup...")
	// 备份
	bodyBytes, _ = ioutil.ReadFile(url.Path)
	if err != nil {
		seelog.Error(err)
		return
	}
	// 将备份的地址传过去加密
	encryptData, err = Encrypt(bodyBytes, system.GetConfiguration().BackupKey)
	if err != nil {
		seelog.Error(err)
		return
	}
	// 上传到七牛云
	// 上传凭证
	policy := storage.PutPolicy{
		Scope: system.GetConfiguration().QiniuBucket,
	}
	// 地址
	mac := qbox.NewMac(system.GetConfiguration().QiniuAccessKey, system.GetConfiguration().QiniuSecretKey)
	// 返回的token
	token := policy.UploadToken(mac)
	config := storage.Config{}
	// 上传者
	uploader := storage.NewFormUploader(&config)
	// 放置临时的
	putExtra := storage.PutExtra{}
	filename := fmt.Sprintf("wcgblog_%s.db", GetCurrentTime().Format("20060102150405"))
	// 上传
	err = uploader.Put(context.Background(), &ret, token, filename, bytes.NewReader(encryptData), int64(len(encryptData)), &putExtra)
	if err != nil {
		seelog.Debug("backup error :%v", err)
		return
	}

	seelog.Debug("backup succes")
	return err
}
